package kk;

import java.time.LocalTime;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务
 *
 * @author 王志强
 * @date 2021-11-16
 */
public class Tim {
    public static void main(String[] args) {
        addOneTask();
    }

    /**
     * timer串行执行，会抛异常
     */
    public static void timer1() {

        Timer t = new Timer();
        t.schedule(new TimerTask() {

            @Override
            public void run() {
                // TODO
                System.out.println("1111111:   " + LocalTime.now());
                throw new RuntimeException();

            }
        }, 5000);


        Timer t2 = new Timer();
        t2.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("2222222:   " + LocalTime.now());
            }
        }, 3000);
    }


    /**
     * 定时任务，推荐使用这种
     * <p>
     * ScheduledExecutorService,并行执行，解决报错
     */
    public static void addOneTask() {
        System.out.println("hello world-2-1:" + System.currentTimeMillis());
        Runnable task = new Runnable() {
            @Override
            public void run() {
                System.out.println("hello world-2-2:" + System.currentTimeMillis());
            }
        };
        ScheduledExecutorService pool = new ScheduledThreadPoolExecutor(1, new ThreadPoolExecutor.AbortPolicy());

        pool.scheduleWithFixedDelay(task, 1000, 1000, TimeUnit.MILLISECONDS);
        Runnable task1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("hello world-1:" + System.currentTimeMillis());
                throw new RuntimeException();
            }
        };


        pool.schedule(task1, 1000 * 5, TimeUnit.MILLISECONDS);
    }
}
